<template>
    <el-div class="navbar">
        <el-div class="navbar-left">
            <a @click="goBackHome" class="dropbtn"><el-i class="fas fa-home"></el-i></a> 
            <el-p class="welcome-message">{{message}}</el-p>
        </el-div>
      <el-div class="navbar-center">
          <el-div class="dropdown">
              <a @click="goToAllBoke" class="dropbtn">全部文章</a>
          </el-div>
          <a target="_blank" href="http://bilibili.com" class="dropbtn">友链</a>
          <el-div class="dropdown">
              <a class="dropbtn" @click="goToUserUpdate">我的</a>
              <el-div class="dropdown-content">
                  <a @click="goToMyBlog(UserID)"><i class="fa fa-blog"></i>我的博客</a>
                  <a @click="goToAddBoke"><i class="fas fa-edit"></i>发布博客</a>
                  <!-- <a href="#"><i class="fa fa-file-powerpoint"></i>PPT收藏</a> -->
              </el-div>
          </el-div>
  
      </el-div>
      <el-div class="navbar-right">
          <a href="#"><i class="fas fa-book"></i></a>
          <a href="#"><i class="fas fa-podcast"></i></a>
          <router-link to="/search">
                <i class="fas fa-search"></i>
          </router-link>
          <el-div class="dropdown">
              <a href="#" class="dropbtn"><i class="fa fa-cog"></i></a>
              <el-div class="dropdown-content" style="position: absolute; left: auto; right: 0; transform: translateX(0); min-width: 150px;">
                  <a href="#" id="theme-toggle"><i id="theme-icon" class="fas fa-moon" @click="toggleTheme"></i></a>
                  <a @click="goBackLogin"><i class="fas fa-sign-out-alt"></i> 退出登录</a>
              </el-div>
          </el-div>
      </el-div>
  </el-div>
  <el-div class="announcement" style="margin-top: 20px;margin-bottom: 20px">
      <i class="announcement_icon fa fa-bullhorn" id="announcement_icon"></i>
      <el-div class="announcement-content-container">
          <el-div class="announcement_content" id="announcement1">
              音乐api失效了，更换了Meting.min.js里面的api，保存到了自己的cdn上
          </el-div>
          <el-div class="announcement_content" id="announcement2">
              网站维护时间调整为每周五晚上10点至次日早上6点。
          </el-div>
          <el-div class="announcement_content" id="announcement3">
              新功能上线，欢迎大家体验并提出宝贵意见。
          </el-div>
      </el-div>
  </el-div>
  <<el-div class="container">
    <div style="height: 400px;">
      <div v-for="post in posts.slice(0, 2)" :key="post.PostID" @click="goToBokeInfo(post.PostID)" class="box" :style="{ backgroundImage: 'url(' + post.PictureUrl + ')', marginTop: '30px', height: '250px' }">
        <h1>{{ post.PostTitle }}</h1>
        <div class="content">
        </div>
      </div>
      <div class="small-boxes" style="margin-left: 20px">
        <a @click="goToHotBoke"><div class="small-box" id="box1">热门文章</div></a>
        <a @click="goToBokeColumn"><div class="small-box" id="box2">文章分类</div></a>
        <router-link to="/pt"><div class="small-box" id="box3">文章标签</div></router-link>
                    
                  
      </div>
    </div>
    <a>
      <div v-if="posts[3]" :key="posts[3].PostID" @click="goToBokeInfo(posts[3].PostID)" class="box" :style="{ backgroundImage: 'url(' + posts[3].PictureUrl + ')', marginTop: '30px', height: '290px' }">
        <h1>{{ posts[3].PostTitle }}</h1>
        <div class="content">
        </div>
      </div>

      <div v-if="posts[2]" :key="posts[2].PostID" @click="goToBokeInfo(posts[2].PostID)" class="box" :style="{ backgroundImage: 'url(' + posts[2].PictureUrl + ')', marginTop: '30px', height: '290px' }">
        <h1>{{ posts[2].PostTitle }}</h1>
        <div class="content">
        </div>
      </div>
    </a>
  </el-div>
</template>
  
<script>
import { useUserStore } from '../store/useUserstore';
import { ref, onMounted } from 'vue';
import instance from '../api/server';
import { RouterLink } from 'vue-router';

export default {
  data() {
    return {
      posts: [],
      Picture: [],
      message: null,
      currentIndex: 0,
      dropdowns: [],
      announcements: [],
      UserID: 0 ,
    };
  },
  created() {
    this.fetchPosts();
  },
  methods: {
    async getPictureUrl(post) {
      try {
        const response = await instance.get(`/myinfo/blog/picture/${post.PostID}`);
        post.PictureUrl = response.data.data[0].PictureUrl; // 将图片地址存储在 post 对象中
      } catch (error) {
        console.error('获取图片失败', error);
        post.PictureUrl = '/src/assets/login.jpg'; // 默认图片
      }
    },
    // 获取博文数据
    async fetchPosts() {
      try {
        const response = await instance.get('/myinfo/blog/getallpost');
        this.posts = response.data.data;
        console.log('获取的帖子数据:', this.posts); // 添加日志
        console.log(JSON.stringify(this.posts,null,2));
        // 为每篇博文获取图片
        for (const post of this.posts) {
          await this.getPictureUrl(post);
          console.log('获取的图片地址:',JSON.stringify(post.PictureUrl,null,2));
        }
        const PostDetail = useUserStore();
        PostDetail.setPost(this.posts);

        console.log('posts:', this.posts);
        console.log('store post:', PostDetail.post);

        if (PostDetail.post && PostDetail.post.PostID) {
          console.log(PostDetail.post.PostID + " 无敌了");
        } else {
          console.log("PostID 未找到");
        }

      } catch (error) {
        console.error('获取博文失败', error);
      }
    },
    goToBokeInfo(PostID) {
      this.$router.push(`/bokeinfo/${PostID}`).then(() => {
        window.location.reload();
      });
    },
    goToMyBlog( UserID ) {
      this.$router.push(`/myboke/${UserID}`).then(() => {
        window.location.reload();
      });
    },
    goBackLogin() {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      this.$router.push("/").then(() => {
        window.location.reload();
      });
    },
    goBackHome() {
      window.location.reload();
    },
    goToAllBoke() {
      this.$router.push("/allboke");
    },
    goToHotBoke() {
      this.$router.push("/hotboke").then(() => {
        window.location.reload();
      });
    },
    goToUserUpdate() {
      this.$router.push("/userupdate").then(() => {
        window.location.reload();
      });
    },
    goToBokeColumn() {
      this.$router.push("/bokecolumn").then(() => {
        window.location.reload();
      });
    },
    goToFakeBoke() {
      this.$router.push("/fakebokeinfo").then(() => {
        window.location.reload();
      });
    },
    goToAddBoke() {
      this.$router.push("/addbokeinfo").then(() => {
        window.location.reload();
      })
      },
    // 切换公告
    showNextAnnouncement() {
      if (this.announcements.length > 0) {
        this.announcements[this.currentIndex].style.opacity = '0';
        setTimeout(() => {
          this.announcements[this.currentIndex].style.display = 'none';
          this.currentIndex = (this.currentIndex + 1) % this.announcements.length;
          this.announcements[this.currentIndex].style.display = 'flex';
          setTimeout(() => {
            this.announcements[this.currentIndex].style.opacity = '1';
          }, 100);
        }, 3000);
      }
    },
    // 处理下拉菜单的显示与隐藏
    toggleDropdown(event) {
      const dropdownContent = event.target.querySelector('.dropdown-content');
      if (dropdownContent) {
        dropdownContent.style.display = 'flex';
        setTimeout(() => {
          dropdownContent.style.opacity = '1'; 
          dropdownContent.style.visibility = 'visible';
        }, 100);
      }
    },
    hideDropdown(event) {
      const dropdownContent = event.target.querySelector('.dropdown-content');
      if (dropdownContent) {
        dropdownContent.style.opacity = '1';
        dropdownContent.style.visibility = 'hidden';
        setTimeout(() => {
          dropdownContent.style.display = 'none';
        }, 2000);
      }
    }
  },
  mounted() {
    // 初始化用户信息
    const UserDetail = useUserStore();
    if (UserDetail.userInfo.UserAccount != null) {
      this.message = "欢迎回来, " + UserDetail.userInfo.UserAccount;
    }

    if (UserDetail.userInfo.UserID != null) {
      this.UserID = UserDetail.userInfo.UserID;
    }

    // 获取下拉菜单和公告的元素
    this.dropdowns = document.querySelectorAll('.dropdown');
    this.announcements = document.querySelectorAll('.announcement_content');

    // 初始化公告的显示
    this.announcements.forEach((announcement, index) => {
      if (index !== 0) {
        announcement.style.display = 'none';
      }
    });

    // 设置下拉菜单的鼠标事件监听
    this.dropdowns.forEach(dropdown => {
      dropdown.addEventListener('mouseenter', this.toggleDropdown);
      dropdown.addEventListener('mouseleave', this.hideDropdown);
    });

    // 设置公告定时切换
    setInterval(this.showNextAnnouncement, 4000); // 每4秒钟切换一次公告
  },
  beforeDestroy() {
    // 清除事件监听器
    this.dropdowns.forEach(dropdown => {
      dropdown.removeEventListener('mouseenter', this.toggleDropdown);
      dropdown.removeEventListener('mouseleave', this.hideDropdown);
    });
  }
};

  document.body.style.backgroundColor = "#eaf4ff";
</script>


<style src="../assets/style/Home.css" scoped>
</style>


